package com.example.accessdemo.controller;

import com.example.accessdemo.service.MyThreadService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @ClassName ThreadDemoController
 * @Description 将list数据由同步单线程for循环处理改造为多线程异步处理
 * @Author kuangdda
 * @Date 16:37 2023/1/9
 * @Version 1.0
 **/
@RestController
@RequestMapping("/demo")
public class ThreadDemoController {


    @Resource
    private MyThreadService myThreadService;

    /**
     * 测试多线程数据处理
     * 使用多线程的方式来处理for循环，并在所有线程都处理完毕后返回最终结果
     * @return
     */
    @GetMapping("testSync")
    public String testSync(){
        List<Map<String, Object>> resultList = Collections.synchronizedList(new ArrayList<>());

        List<Integer> integerList = new ArrayList<>();

        /**
         * 模拟处理1000000条数据
         */
        for (int i = 0; i < 1000000;i++){
            integerList.add(i);
        }

        /**
         * 创建多线程处理
         */
        Future<Boolean> booleanFuture = myThreadService.sysThread(integerList, 20, resultList);

        try {
            if(booleanFuture.get()){
                return String.valueOf( resultList.size());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    
    @GetMapping("testSyncNew")
    public String testSyncNew(){
        List<Map<String, Object>> resultList = Collections.synchronizedList(new ArrayList<>());
        
        List<Integer> integerList = new ArrayList<>();
        
        /**
         * 模拟处理1000000条数据
         */
        for (int i = 0; i < 1000000;i++){
            integerList.add(i);
        }
        
        /**
         * 创建多线程处理
         */
        Future<Boolean> booleanFuture = myThreadService.sysThread(integerList,  resultList);
        
        try {
            if(booleanFuture.get()){
                return String.valueOf( resultList.size());
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
